import { defineComponent, ref, watch } from 'vue';
import { MciDialog, MciButton, MciMessage, MciInput } from '@/components/base';
import { ElForm, ElFormItem, ElInputNumber } from 'element-plus';
import { postDecisionFlowWeightAssign } from '@/api';

export const AssignFlowWeight = defineComponent({
  props: {
    flowList: {
      type: Array,
      default: () => []
    }
  },
  emits: ['refresh', 'update:modelValue'],
  setup(props, { emit }) {
    const loading = ref(false);
    const flowVars = ref<Array<any>>([]);
    const originList = ref<Array<any>>([]);
    const newFlowList = ref<Array<any>>([]);
    const formRef = ref<InstanceType<typeof ElForm>>();

    const initData = () => {
      newFlowList.value = props.flowList.filter((item) => item.status === 2);
      originList.value = props.flowList.concat();
      newFlowList.value.forEach((item) => {
        flowVars.value[item.versionNo] = item.weight;
      });
    };

    const onConfirm = async () => {
      try {
        await formRef.value?.validate();
        loading.value = true;
        const params = originList.value.map((item) => {
          return {
            flowId: item.id,
            weight: flowVars.value[item.versionNo] === undefined || flowVars.value[item.versionNo] === null ? item.weight : flowVars.value[item.versionNo]
          };
        });
        console.log('🚀 ~ onConfirm ~ params:', params);
        // 计算所有weight的总和
        const totalWeight = params.reduce((total, item) => total + (item.weight || 0), 0);
        if (totalWeight !== 100) {
          MciMessage({
            message: '权重总和必须为100',
            type: 'error'
          });
          return;
        } else {
          const data = await postDecisionFlowWeightAssign({ flowWeights: params });
          MciMessage({
            message: '设置成功',
            type: 'success'
          });
          emit('refresh');
          handleClose();
        }
      } catch (error) {
      } finally {
        loading.value = false;
      }
    };

    const handleClose = () => {
      emit('update:modelValue', false);
    };

    initData();

    return () => {
      return (
        <MciDialog width={540} title="设置版本权重" modelValue={true} onClose={handleClose} customClass="max-height-dialog">
          {{
            default() {
              return (
                <ElForm ref={formRef} model={flowVars.value} labelPosition="top">
                  {newFlowList.value.map((field) => (
                    <ElFormItem
                      style={{ display: 'flex!important' }}
                      label={`${field.versionNo}（已发布）:`}
                      prop={field.versionNo}
                      rules={[
                        {
                          required: true,
                          message: `请输入${field.versionNo}版本的权重`,
                          trigger: ['change', 'blur']
                        }
                      ]}>
                      <ElInputNumber
                        v-model={flowVars.value[field.versionNo]}
                        max="100"
                        min="0"
                        controls-position="right"
                        onChange={(value) => {
                          flowVars.value[field.versionNo] = parseInt(value, 10);
                        }}
                      />
                    </ElFormItem>
                  ))}
                  <ElFormItem label="隐藏" style="display: none;" prop="hidden">
                    <MciInput />
                  </ElFormItem>
                </ElForm>
              );
            },
            footer() {
              return (
                <>
                  <MciButton onClick={handleClose} loading={loading.value}>
                    取消
                  </MciButton>
                  <MciButton type="primary" onClick={onConfirm} loading={loading.value}>
                    确定
                  </MciButton>
                </>
              );
            }
          }}
        </MciDialog>
      );
    };
  }
});
